package com.example.wan_android.ui.activity

import android.view.View
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.wan_android.BR
import com.example.wan_android.R
import com.example.wan_android.adapter.SearchResultAdapter
import com.example.wan_android.databinding.ActivitySearchResultBinding
import com.example.wan_android.tools.SpacesItemDecoration
import com.example.wan_android.viewmodel.SearchResultViewModel

class SearchResultActivity : BaseActivity<ActivitySearchResultBinding, SearchResultViewModel>(
    SearchResultViewModel::class.java,
    R.layout.activity_search_result,
    BR.viewModel
) {
    private val adapter by lazy {
        SearchResultAdapter(mViewModel!!)
    }

    override fun initView() {
        mViewModel?.isSuccess?.observe(this) {
            if (it) {
                mViewDataBinding?.ivEmpty?.visibility = View.GONE
                mViewDataBinding?.rvSearchResultBody?.visibility = View.VISIBLE
            } else {
                mViewDataBinding?.ivEmpty?.visibility = View.VISIBLE
                mViewDataBinding?.rvSearchResultBody?.visibility = View.GONE
            }
        }
        val title = intent.getStringExtra(SearchResultViewModel.title)
        val word = intent.getStringExtra(SearchResultViewModel.searchWord)
        mViewModel?.mTitle = title ?: ""
        mViewModel?.mSearchWord = word ?: ""
        mViewModel?.getResultData()
        mViewDataBinding?.nvNestedScroll?.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            if (isNearBottom(scrollY)) {
                mViewModel?.getResultData()
            }
        })
        mViewDataBinding?.rvSearchResultBody?.adapter = adapter
        mViewDataBinding?.rvSearchResultBody?.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        mViewDataBinding?.rvSearchResultBody?.addItemDecoration(SpacesItemDecoration(40))
        mViewModel?.contentLiveData?.observe(this) {
            it.onSuccess {
                adapter.addListData(it)
            }
            it.onFailure {
            }
        }
    }

    // 判断是否接近底部
    private fun isNearBottom(scrollY: Int): Boolean {
        val contentHeight = mViewDataBinding?.nvNestedScroll?.getChildAt(0)?.height
        val viewHeight = mViewDataBinding?.nvNestedScroll?.height

        return scrollY >= (contentHeight!! - viewHeight!!)
    }
}